import { genChartByAi } from '@/services/bi/bijiekou';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Card, Col, Divider, Form, Input, message, Row, Select, Space, Spin, Upload } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import React, { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';
import { PageContainer } from '@ant-design/pro-layout';
import { consumeAmount } from '@/services/user/yonghujiekou';
import ModalAsync from '@/components/ModalAsync';
import moment from 'moment';

/**
 * 添加图表页面
 * @constructor
 */
const AddChart: React.FC = () => {
  const [chart, setChart] = useState<API.ChartVo>();
  const [option, setOption] = useState<any>();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [openModal, setOpenModal] = useState<any>(false)
  const [spend, setSpend] = useState<number>(1);
  const [formData, setFormData] = useState<any>()
  const [form] = Form.useForm();

  /**
   * 提交
   * @param values
   */
  const onFinish = async (values: any) => {
    // 避免重复提交
    if (submitting) {
      return;
    }
    
    if (values.file.file.size > 1024 * 10) {
      setSpend(2)
    } else if (values.file.file.size > 1024 * 100) {
      setSpend(3)
    } else if (values.file.file.size > 1024 * 1000){
      message.error('文件大小不能超过1M')
      return
    }
    setOpenModal(true)
    setOption(undefined);
    setFormData(values)
  };

  useEffect(() => {
    
  },[spend])

  const generateContent = () => {
    return `确定要花费${spend}豆币吗？`;
  };

  const ok = async () => {
    setSubmitting(true)
    setOpenModal(false)
    const values = formData
    // 对接后端，上传数据
    const params = {
      ...values,
      file: undefined,
    };
    setChart({})
    try {
      const re = await consumeAmount({ amount: spend });
      if (re.code != 0) {
        message.error(re.message);
        setSubmitting(false);
        return;
      }
      const res = await genChartByAi(params, {}, values.file.file.originFileObj);
      if (!res?.data) {
        message.error('分析失败');
      } else {
        message.success('分析成功');
        const chartOption = JSON.parse(res.data.genChart ?? '');
        if (!chartOption) {
          throw new Error('图表代码解析错误')
        } else {
          setChart(res.data);
          setOption(chartOption);
          form.resetFields()
        }

      }
    } catch (e: any) {
      message.error('分析失败，' + e.message);
    }
    setSubmitting(false);
    return true;
  };



  return (
    <PageContainer ghost>
      <div className="add-chart">
        <Row gutter={24}>
          <Col span={12}>
            <Card title="智能分析">
              <Form form={form} name="addChart" labelAlign="left" labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }} onFinish={onFinish} initialValues={{}}>
                <Form.Item
                  name="goal"
                  label="分析目标"
                  rules={[{ required: true, message: '请输入分析目标' }]}
                >
                  <TextArea placeholder="请输入你的分析需求，比如：分析网站用户的增长情况" />
                </Form.Item>
                <Form.Item name="name" label="图表名称"  rules={[{ required: true, message: '请输入图表名称' }]}>
                  <Input placeholder="请输入图表名称" />
                </Form.Item>
                <Form.Item name="chartType" label="图表类型" rules={[{ required: true, message: '请选择图表类型' }]}>
                  <Select
                    options={[
                      { value: '折线图', label: '折线图' },
                      { value: '柱状图', label: '柱状图' },
                      { value: '堆叠图', label: '堆叠图' },
                      { value: '饼图', label: '饼图' },
                      { value: '雷达图', label: '雷达图' },
                    ]}
                  />
                </Form.Item>
                <Form.Item name="file" label="原始数据" rules={[{ required: true, message: '请上传数据' }]}>
                  <Upload name="file" maxCount={1}>
                    <Button icon={<UploadOutlined />}>上传 CSV 文件</Button>
                  </Upload>
                </Form.Item>

                <Form.Item wrapperCol={{ span: 16, offset: 4 }}>
                  <Space>
                    <Button type="primary" htmlType="submit" loading={submitting} disabled={submitting}>
                      提交
                    </Button>
                    <Button htmlType="reset">重置</Button>
                  </Space>
                </Form.Item>
              </Form>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="分析结论">
            {chart?.genResult ?<>
                <div style={{ marginBottom: 16 }} />
                <p>{'分析目标：' + chart?.goal}</p>
                <div style={{ marginBottom: 16 }} />
                <ReactECharts option={chart?.genChart && JSON.parse(chart?.genChart)} />
                <div style={{ marginBottom: 16 }} />
                <p>{'分析结果：' + chart?.genResult}</p>
              </>:'请先在左侧进行提交'}
              <Spin spinning={submitting} />
            </Card>
            <Divider />
          </Col>
        </Row>
      </div>
      <ModalAsync
        key={1}
        open={openModal}
        setVisible={setOpenModal}
        title={'消费'}
        ok={ok}
        generateContent={generateContent}
      />
    </PageContainer>
  );
};
export default AddChart;
